/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.hiddenreport.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.appletuser.entity.AppletUser;
import vip.xiaonuo.biz.modular.appletuser.mapper.AppletUserMapper;
import vip.xiaonuo.biz.modular.hiddenreport.entity.ReportAuditRecord;
import vip.xiaonuo.biz.modular.hiddenreport.enums.*;
import vip.xiaonuo.biz.modular.hiddenreport.mapper.ReportAuditRecordMapper;
import vip.xiaonuo.biz.modular.hiddenreport.param.*;
import vip.xiaonuo.biz.modular.org.entity.BizOrg;
import vip.xiaonuo.biz.modular.org.mapper.BizOrgMapper;
import vip.xiaonuo.biz.modular.rewardslog.service.RewardsLogService;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.mapper.BizUserMapper;
import vip.xiaonuo.biz.modular.watchtask.mapper.TaskMapper;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.hiddenreport.entity.HiddenReport;
import vip.xiaonuo.biz.modular.hiddenreport.mapper.HiddenReportMapper;
import vip.xiaonuo.biz.modular.hiddenreport.service.HiddenReportService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 隐患上报信息Service接口实现类
 *
 * @author H
 * @date  2025/10/17 16:36
 **/
@Service
public class HiddenReportServiceImpl extends ServiceImpl<HiddenReportMapper, HiddenReport> implements HiddenReportService {
    @Resource
    private AppletUserMapper appletUserMapper;
    @Resource
    private ReportAuditRecordMapper reportAuditRecordMapper;
    @Resource
    private BizUserMapper bizUserMapper;
    @Resource
    private BizOrgMapper bizOrgMapper;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private RewardsLogService rewardsLogService;

    @Override
    public Page<HiddenReport> page(HiddenReportPageParam hiddenReportPageParam) {
        QueryWrapper<HiddenReport> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getUserName())) {
            queryWrapper.lambda().like(HiddenReport::getUserName, hiddenReportPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getUserPhone())) {
            queryWrapper.lambda().like(HiddenReport::getUserPhone, hiddenReportPageParam.getUserPhone());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenType())) {
            queryWrapper.lambda().eq(HiddenReport::getHiddenType, hiddenReportPageParam.getHiddenType());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getApproval())) {
            queryWrapper.lambda().eq(HiddenReport::getApproval, hiddenReportPageParam.getApproval());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenLevel())) {
            queryWrapper.lambda().eq(HiddenReport::getHiddenLevel, hiddenReportPageParam.getHiddenLevel());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getRectificationOrgId())) {
            queryWrapper.lambda().eq(HiddenReport::getRectificationOrgId, hiddenReportPageParam.getRectificationOrgId());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getCurrentStatus())) {
            queryWrapper.lambda().eq(HiddenReport::getCurrentStatus, hiddenReportPageParam.getCurrentStatus());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getVerifyUserName())) {
            queryWrapper.lambda().like(HiddenReport::getVerifyUserName, hiddenReportPageParam.getVerifyUserName());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenAddr())) {
            queryWrapper.lambda().like(HiddenReport::getHiddenAddr, hiddenReportPageParam.getHiddenAddr());
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getReportDateStart(),hiddenReportPageParam.getReportDateEnd())) {
            queryWrapper.lambda().between(HiddenReport::getCreateTime, DateUtil.beginOfDay(hiddenReportPageParam.getReportDateStart()), DateUtil.endOfDay(hiddenReportPageParam.getReportDateEnd()));
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getVerifyDateStart(),hiddenReportPageParam.getVerifyDateEnd())) {
            queryWrapper.lambda().between(HiddenReport::getVerifyTime, DateUtil.beginOfDay(hiddenReportPageParam.getVerifyDateStart()), DateUtil.endOfDay(hiddenReportPageParam.getVerifyDateEnd()));
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getSortField(), hiddenReportPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(hiddenReportPageParam.getSortOrder());
            queryWrapper.orderBy(true, hiddenReportPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(hiddenReportPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(HiddenReport::getCreateTime);
        }
        Page<HiddenReport> result = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        for(HiddenReport hiddenReport:result.getRecords()){
            if(ObjectUtil.isNotEmpty(hiddenReport.getSuggestionRewards())){
                hiddenReport.setSuggestionRewards(hiddenReport.getSuggestionRewards()/100);
            }
            if(ObjectUtil.isNotEmpty(hiddenReport.getHiddenRewards())){
                hiddenReport.setHiddenRewards(hiddenReport.getHiddenRewards()/100);
            }
        }
        return result;
    }

    @Override
    public Page<HiddenReport> waitAuditPage(HiddenReportPageParam hiddenReportPageParam) {
        QueryWrapper<HiddenReport> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getUserName())) {
            queryWrapper.lambda().like(HiddenReport::getUserName, hiddenReportPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getUserPhone())) {
            queryWrapper.lambda().like(HiddenReport::getUserPhone, hiddenReportPageParam.getUserPhone());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenType())) {
            queryWrapper.lambda().eq(HiddenReport::getHiddenType, hiddenReportPageParam.getHiddenType());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getApproval())) {
            queryWrapper.lambda().eq(HiddenReport::getApproval, hiddenReportPageParam.getApproval());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenLevel())) {
            queryWrapper.lambda().eq(HiddenReport::getHiddenLevel, hiddenReportPageParam.getHiddenLevel());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getRectificationOrgId())) {
            queryWrapper.lambda().eq(HiddenReport::getRectificationOrgId, hiddenReportPageParam.getRectificationOrgId());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getVerifyUserName())) {
            queryWrapper.lambda().like(HiddenReport::getVerifyUserName, hiddenReportPageParam.getVerifyUserName());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenAddr())) {
            queryWrapper.lambda().like(HiddenReport::getHiddenAddr, hiddenReportPageParam.getHiddenAddr());
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getReportDateStart(),hiddenReportPageParam.getReportDateEnd())) {
            queryWrapper.lambda().between(HiddenReport::getCreateTime, DateUtil.beginOfDay(hiddenReportPageParam.getReportDateStart()), DateUtil.endOfDay(hiddenReportPageParam.getReportDateEnd()));
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getVerifyDateStart(),hiddenReportPageParam.getVerifyDateEnd())) {
            queryWrapper.lambda().between(HiddenReport::getVerifyTime, DateUtil.beginOfDay(hiddenReportPageParam.getVerifyDateStart()), DateUtil.endOfDay(hiddenReportPageParam.getVerifyDateEnd()));
        }
        // 判断是否核实人
        if(StpUtil.hasRole("role_verify")){
            queryWrapper.lambda().eq(HiddenReport::getApproval,AuditStatusEnum.WAIT_VERIFY.getValue());
            queryWrapper.lambda().eq(HiddenReport::getVerifyUserId,StpLoginUserUtil.getLoginUser().getId());
        }
        // 判断是否审核管理员
        if(StpUtil.hasRole("role_audit")){
            queryWrapper.lambda().in(HiddenReport::getApproval,AuditStatusEnum.WAIT_ALLOCATE.getValue(),AuditStatusEnum.MGR_AUDIT.getValue());
        }
        // 判断是否监督站站长
        if(StpUtil.hasRole("role_supervise")){
            queryWrapper.lambda().eq(HiddenReport::getApproval,AuditStatusEnum.SUPERVISE_AUDIT.getValue());
        }
        // 判断是否业务部门领导
        if(StpUtil.hasRole("role_biz")){
            queryWrapper.lambda().eq(HiddenReport::getApproval,AuditStatusEnum.BIZ_AUDIT.getValue());
            queryWrapper.lambda().eq(HiddenReport::getRectificationUserId,StpLoginUserUtil.getLoginUser().getId());
        }
        // 判断是否安全部门领导
        if(StpUtil.hasRole("role_safety")){
            queryWrapper.lambda().eq(HiddenReport::getApproval,AuditStatusEnum.SAFETY_AUDIT.getValue());
        }
        // 判断是否分管领导
        if(StpUtil.hasRole("role_charge_leader")){
            queryWrapper.lambda().eq(HiddenReport::getApproval,AuditStatusEnum.CHARGE_AUDIT.getValue());
            queryWrapper.lambda().eq(HiddenReport::getChargeLeaderId,StpLoginUserUtil.getLoginUser().getId());
        }
        // 判断是否主要领导
        if(StpUtil.hasRole("role_main_leader")){
            queryWrapper.lambda().eq(HiddenReport::getApproval,AuditStatusEnum.MAIN_AUDIT.getValue());
            queryWrapper.lambda().eq(HiddenReport::getMainLeaderId,StpLoginUserUtil.getLoginUser().getId());
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getSortField(), hiddenReportPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(hiddenReportPageParam.getSortOrder());
            queryWrapper.orderBy(true, hiddenReportPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(hiddenReportPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(HiddenReport::getCreateTime);
        }
        Page<HiddenReport> result = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        for(HiddenReport hiddenReport:result.getRecords()){
            if(ObjectUtil.isNotEmpty(hiddenReport.getSuggestionRewards())){
                hiddenReport.setSuggestionRewards(hiddenReport.getSuggestionRewards()/100);
            }
            if(ObjectUtil.isNotEmpty(hiddenReport.getHiddenRewards())){
                hiddenReport.setHiddenRewards(hiddenReport.getHiddenRewards()/100);
            }
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(HiddenReportAddParam hiddenReportAddParam) {
        HiddenReport hiddenReport = BeanUtil.toBean(hiddenReportAddParam, HiddenReport.class);
        hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_VERIFY.getValue());
        hiddenReport.setApproval(AuditStatusEnum.WAIT_ALLOCATE.getValue());
        AppletUser appletUser = appletUserMapper.getByPhone(hiddenReportAddParam.getUserPhone());
        if(ObjectUtil.isNotEmpty(appletUser)){
            hiddenReport.setUserId(appletUser.getUserId());
            hiddenReport.setUserName(appletUser.getUserName());
            hiddenReport.setPlatformUserId(appletUser.getPlatformUserId());
        }
        this.save(hiddenReport);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(HiddenReportEditParam hiddenReportEditParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportEditParam.getReportId());
        BeanUtil.copyProperties(hiddenReportEditParam, hiddenReport);
        AppletUser appletUser = appletUserMapper.getByPhone(hiddenReportEditParam.getUserPhone());
        if(ObjectUtil.isNotEmpty(appletUser)){
            hiddenReport.setUserId(appletUser.getUserId());
            hiddenReport.setUserName(appletUser.getUserName());
            hiddenReport.setPlatformUserId(appletUser.getPlatformUserId());
        }
        this.updateById(hiddenReport);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<HiddenReportIdParam> hiddenReportIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(hiddenReportIdParamList, HiddenReportIdParam::getReportId));
    }

    @Override
    public HiddenReport detail(HiddenReportIdParam hiddenReportIdParam) {
        return this.queryEntity(hiddenReportIdParam.getReportId());
    }

    @Override
    public HiddenReport queryEntity(String id) {
        HiddenReport hiddenReport = this.getById(id);
        if(ObjectUtil.isEmpty(hiddenReport)) {
            throw new CommonException("隐患上报信息不存在，id值为：{}", id);
        }
        return hiddenReport;
    }

    @Override
    public void allocateVerifyUser(HiddenReportAllocateParam hiddenReportAllocateParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportAllocateParam.getReportId());
        if(ObjectUtil.notEqual(hiddenReport.getApproval(), AuditStatusEnum.WAIT_ALLOCATE.getValue())){
            throw new CommonException(ReportErroEnum.APPROVAL_STATUS_ERRO.getMsg());
        }
        hiddenReport.setVerifyUserId(hiddenReportAllocateParam.getVerifyUserId());
        // 查询核实人
        BizUser bizUser = bizUserMapper.selectById(hiddenReportAllocateParam.getVerifyUserId());
        hiddenReport.setVerifyUserName(bizUser.getName());
        hiddenReport.setApproval(AuditStatusEnum.WAIT_VERIFY.getValue());
        AppletUser appletUser = appletUserMapper.getByPlatformUserId(bizUser.getId());
        if(ObjectUtil.isNotEmpty(appletUser)){
            hiddenReport.setVerifyUserAppletId(appletUser.getUserId());
        }
        this.updateById(hiddenReport);
    }

    @Override
    public void verifyHidden(HiddenReportVerifyParam hiddenReportVerifyParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportVerifyParam.getReportId());
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        if(ObjectUtil.notEqual(hiddenReport.getVerifyUserId(), saBaseLoginUser.getId())){
            throw new CommonException(ReportErroEnum.USER_NOT_MATCH.getMsg());
        }
        if(ObjectUtil.notEqual(hiddenReport.getApproval(), AuditStatusEnum.WAIT_VERIFY.getValue())){
            throw new CommonException(ReportErroEnum.APPROVAL_STATUS_ERRO.getMsg());
        }
        hiddenReport.setVerifyTime(DateUtil.date());
        hiddenReport.setVerifyResult(hiddenReportVerifyParam.getVerifyResult());
        hiddenReport.setVerifySituation(hiddenReportVerifyParam.getVerifySituation());
        hiddenReport.setHiddenAddr(hiddenReportVerifyParam.getHiddenAddr());
        hiddenReport.setVerifyImage(hiddenReportVerifyParam.getVerifyImage());
        if(hiddenReportVerifyParam.getVerifyResult()!=1){
            hiddenReport.setCurrentStatus(ShowStatusEnum.NOT_ADPOT.getValue());
            hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
        }else{
            hiddenReport.setCurrentStatus(ShowStatusEnum.ADPOT.getValue());
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            hiddenReport.setSuggestionMeasures(hiddenReportVerifyParam.getSuggestionMeasures());
        }
        this.updateById(hiddenReport);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mgrAudit(HiddenReportMgrAuditParam hiddenReportMgrAuditParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportMgrAuditParam.getReportId());
        hiddenReport.setSuggestionRewards(hiddenReportMgrAuditParam.getSuggestionRewards()*100.0);
        hiddenReport.setHiddenLevel(hiddenReportMgrAuditParam.getHiddenLevel());
        hiddenReport.setGradingCriteria(hiddenReportMgrAuditParam.getGradingCriteria());
        hiddenReport.setAuditRemark("");
        // 一般问题流程结束
        if(ObjectUtil.equal(HiddenLevelEnum.NORMAL.getValue(), hiddenReport.getHiddenLevel())){
            hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_REWARD.getValue());
            hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
            hiddenReport.setHiddenRewards(hiddenReportMgrAuditParam.getSuggestionRewards()*100.0);
        }else{
            hiddenReport.setApproval(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
            BizOrg bizOrg = bizOrgMapper.selectById(hiddenReportMgrAuditParam.getRectificationOrgId());
            hiddenReport.setRectificationOrgId(hiddenReportMgrAuditParam.getRectificationOrgId());
            hiddenReport.setRectificationOrgName(bizOrg.getName());
            hiddenReport.setRectificationPeriod(hiddenReportMgrAuditParam.getRectificationPeriod());
            // 写入审核记录
            ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
            reportAuditRecord.setReportId(hiddenReport.getReportId());
            reportAuditRecord.setRecordName(AuditFlowNameEnum.MGR_AUDIT.getDesc());
            reportAuditRecord.setCreateUserId(StpLoginUserUtil.getLoginUser().getId());
            reportAuditRecord.setCreateUserName(StpLoginUserUtil.getLoginUser().getName());
            reportAuditRecord.setCurrentStatus(AuditStatusEnum.MGR_AUDIT.getValue());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            // 取监督站站长
            List<BizUser> bizUserList = bizUserMapper.listUserByRoleCode("role_supervise");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new CommonException("未配置监督站站长！");
            }
            if(ObjectUtil.equal(HiddenLevelEnum.LARGER_HIDDEN.getValue(), hiddenReport.getHiddenLevel())||
               ObjectUtil.equal(HiddenLevelEnum.MAJOR_HIDDEN.getValue(), hiddenReport.getHiddenLevel())
            ){

                BizUser chargeLeader = bizUserMapper.selectById(hiddenReportMgrAuditParam.getChargeLeaderId());
                BizUser mainLeader = bizUserMapper.selectById(hiddenReportMgrAuditParam.getMainLeaderId());
                hiddenReport.setChargeLeaderId(hiddenReportMgrAuditParam.getChargeLeaderId());
                hiddenReport.setChargeLeaderName(chargeLeader.getName());
                hiddenReport.setMainLeaderId(hiddenReportMgrAuditParam.getMainLeaderId());
                hiddenReport.setMainLeaderName(mainLeader.getName());
            }
            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setNextStatus(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
            this.reportAuditRecordMapper.insert(reportAuditRecord);
        }
        this.baseMapper.updateById(hiddenReport);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void superviseAudit(HiddenReportSuperviseAuditParam hiddenReportSuperviseAuditParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportSuperviseAuditParam.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.SUPERVISE_AUDIT.getDesc());
        reportAuditRecord.setCreateUserId(StpLoginUserUtil.getLoginUser().getId());
        reportAuditRecord.setCreateUserName(StpLoginUserUtil.getLoginUser().getName());
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
        reportAuditRecord.setRemark(hiddenReportSuperviseAuditParam.getAuditRemark());

        hiddenReport.setHiddenRemark(hiddenReportSuperviseAuditParam.getAuditRemark());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportSuperviseAuditParam.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            // 取审核管理员信息
            List<BizUser> bizUserList = bizUserMapper.listUserByRoleCode("role_audit");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new CommonException("未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());
        }else{
            hiddenReport.setApproval(AuditStatusEnum.BIZ_AUDIT.getValue());
            // 业务部门主任信息
            List<BizUser> bizUserList = bizUserMapper.listOrgRoleUser(hiddenReport.getRectificationOrgId(),"role_biz");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new CommonException("该部门未配置领导信息！");
            }
            // 写入业务部门主任信息
            hiddenReport.setRectificationUserId(bizUserList.get(0).getId());
            hiddenReport.setRectificationUserName(bizUserList.get(0).getId());

            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.BIZ_AUDIT.getValue());
        }
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bizAudit(HiddenReportBizAuditParam hiddenReportBizAuditParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportBizAuditParam.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.BIZ_AUDIT.getDesc());
        reportAuditRecord.setCreateUserId(StpLoginUserUtil.getLoginUser().getId());
        reportAuditRecord.setCreateUserName(StpLoginUserUtil.getLoginUser().getName());
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.BIZ_AUDIT.getValue());
        reportAuditRecord.setRemark(hiddenReportBizAuditParam.getAuditRemark());
        hiddenReport.setHiddenRemark(hiddenReportBizAuditParam.getAuditRemark());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportBizAuditParam.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            // 取审核管理员信息
            List<BizUser> bizUserList = bizUserMapper.listUserByRoleCode("role_audit");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new CommonException("未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());

        }else{
            // 判断是否较大隐患和重大隐患，如果不是则流程结束，如果是则提交到质安环部长审核
            if(hiddenReport.getHiddenLevel()>HiddenLevelEnum.NORMAL_HIDDEN.getValue()){
                hiddenReport.setApproval(AuditStatusEnum.SAFETY_AUDIT.getValue());
                // 取质安环部长信息
                List<BizUser> bizUserList = bizUserMapper.listUserByRoleCode("role_safety");
                if(ObjectUtil.isEmpty(bizUserList)){
                    throw new CommonException("未配置质安环部长！");
                }
                // 写入质安环部长信息
                hiddenReport.setSafetyLeaderId(bizUserList.get(0).getId());
                hiddenReport.setSafetyLeaderName(bizUserList.get(0).getName());

                reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
                reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
                reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
                reportAuditRecord.setNextStatus(AuditStatusEnum.SAFETY_AUDIT.getValue());
            }else{
                hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_REWARD.getValue());
                hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
                reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
                reportAuditRecord.setNextStatus(AuditStatusEnum.FINISHED.getValue());
            }
        }
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void safetyAudit(HiddenReportSafetyAuditParam hiddenReportSafetyAuditParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportSafetyAuditParam.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.SUPERVISE_AUDIT.getDesc());
        reportAuditRecord.setCreateUserId(StpLoginUserUtil.getLoginUser().getId());
        reportAuditRecord.setCreateUserName(StpLoginUserUtil.getLoginUser().getName());
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.SUPERVISE_AUDIT.getValue());
        hiddenReport.setHiddenRemark(hiddenReportSafetyAuditParam.getAuditRemark());
        reportAuditRecord.setRemark(hiddenReportSafetyAuditParam.getAuditRemark());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportSafetyAuditParam.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            // 取审核管理员信息
            List<BizUser> bizUserList = bizUserMapper.listUserByRoleCode("role_audit");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new CommonException("未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());

        }else{
            hiddenReport.setApproval(AuditStatusEnum.CHARGE_AUDIT.getValue());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.CHARGE_AUDIT.getValue());
            reportAuditRecord.setNextUserId(hiddenReport.getChargeLeaderId());
            reportAuditRecord.setNextUserName(hiddenReport.getChargeLeaderName());
        }
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void chargeAudit(HiddenReportChargeAuditParam hiddenReportChargeAuditParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportChargeAuditParam.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.CHARGE_AUDIT.getDesc());
        reportAuditRecord.setCreateUserId(StpLoginUserUtil.getLoginUser().getId());
        reportAuditRecord.setCreateUserName(StpLoginUserUtil.getLoginUser().getName());
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.CHARGE_AUDIT.getValue());
        reportAuditRecord.setRemark(hiddenReportChargeAuditParam.getAuditRemark());
        hiddenReport.setHiddenRemark(hiddenReportChargeAuditParam.getAuditRemark());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportChargeAuditParam.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            // 取审核管理员信息
            List<BizUser> bizUserList = bizUserMapper.listUserByRoleCode("role_audit");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new CommonException("未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());
        }else{
            hiddenReport.setApproval(AuditStatusEnum.MAIN_AUDIT.getValue());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MAIN_AUDIT.getValue());
            reportAuditRecord.setNextUserId(hiddenReport.getMainLeaderId());
            reportAuditRecord.setNextUserName(hiddenReport.getMainLeaderName());
        }
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mainAudit(HiddenReportMainAuditParam hiddenReportMainAuditParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportMainAuditParam.getReportId());
        ReportAuditRecord reportAuditRecord = new ReportAuditRecord();
        reportAuditRecord.setReportId(hiddenReport.getReportId());
        reportAuditRecord.setRecordName(AuditFlowNameEnum.MAIN_AUDIT.getDesc());
        reportAuditRecord.setCreateUserId(StpLoginUserUtil.getLoginUser().getId());
        reportAuditRecord.setCreateUserName(StpLoginUserUtil.getLoginUser().getName());
        reportAuditRecord.setCurrentStatus(AuditStatusEnum.MAIN_AUDIT.getValue());
        reportAuditRecord.setRemark(hiddenReportMainAuditParam.getAuditRemark());
        hiddenReport.setHiddenRemark(hiddenReportMainAuditParam.getAuditRemark());
        if(ObjectUtil.notEqual(AuditResultEnum.PASS.getValue(), hiddenReportMainAuditParam.getAuditResult())){
            hiddenReport.setApproval(AuditStatusEnum.MGR_AUDIT.getValue());
            // 取审核管理员信息
            List<BizUser> bizUserList = bizUserMapper.listUserByRoleCode("role_audit");
            if(ObjectUtil.isEmpty(bizUserList)){
                throw new CommonException("未配置审核管理员！");
            }
            reportAuditRecord.setNextUserId(bizUserList.get(0).getId());
            reportAuditRecord.setNextUserName(bizUserList.get(0).getName());
            reportAuditRecord.setAuditStatus(AuditResultEnum.NOT_PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.MGR_AUDIT.getValue());
        }else{
            hiddenReport.setCurrentStatus(ShowStatusEnum.WAIT_REWARD.getValue());
            hiddenReport.setApproval(AuditStatusEnum.FINISHED.getValue());
            reportAuditRecord.setAuditStatus(AuditResultEnum.PASS.getValue());
            reportAuditRecord.setNextStatus(AuditStatusEnum.FINISHED.getValue());
        }
        this.reportAuditRecordMapper.insert(reportAuditRecord);
        this.baseMapper.updateById(hiddenReport);
    }

    @Override
    public Page<ReportAuditRecord> pageAuditRecord(HiddenReportRecordPageParam hiddenReportRecordPageParam) {
        QueryWrapper<ReportAuditRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ReportAuditRecord::getReportId, hiddenReportRecordPageParam.getReportId());
        if(ObjectUtil.isAllNotEmpty(hiddenReportRecordPageParam.getSortField(), hiddenReportRecordPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(hiddenReportRecordPageParam.getSortOrder());
            queryWrapper.orderBy(true, hiddenReportRecordPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(hiddenReportRecordPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(ReportAuditRecord::getCreateTime);
        }
        return this.reportAuditRecordMapper.selectPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public void issueReward(HiddenReportRewardParam hiddenReportRewardParam) {
        HiddenReport hiddenReport = this.queryEntity(hiddenReportRewardParam.getReportId());
        // 验证状态
        if(ObjectUtil.notEqual(hiddenReport.getApproval(), AuditStatusEnum.FINISHED.getValue())){
            throw new CommonException("审核流程未结束，无法发放奖励！");
        }
        if(ObjectUtil.notEqual(hiddenReport.getCurrentStatus(), ShowStatusEnum.WAIT_REWARD.getValue())){
            throw new CommonException("当前状态不是待发放奖励状态！");
        }
        AppletUser appletUser = appletUserMapper.getByPhone(hiddenReport.getUserPhone());
        if(ObjectUtil.isEmpty(appletUser)){
            throw new CommonException("上报人信息不全，无法发放奖励！");
        }
        hiddenReport.setHiddenRewards(hiddenReportRewardParam.getHiddenRewards()*100);
        hiddenReport.setCurrentStatus(ShowStatusEnum.FINISHED.getValue());
        this.baseMapper.updateById(hiddenReport);
        //调用接口发放奖励
        rewardsLogService.reportRewards(hiddenReport, appletUser);
    }

    @Override
    public Page<HiddenReport> waitTaskPage(HiddenReportPageParam hiddenReportPageParam) {
        List<String> reportIds = this.taskMapper.listProgressTaskReportIds();
        QueryWrapper<HiddenReport> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getUserName())) {
            queryWrapper.lambda().like(HiddenReport::getUserName, hiddenReportPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getUserPhone())) {
            queryWrapper.lambda().like(HiddenReport::getUserPhone, hiddenReportPageParam.getUserPhone());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenType())) {
            queryWrapper.lambda().eq(HiddenReport::getHiddenType, hiddenReportPageParam.getHiddenType());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getRectificationOrgId())) {
            queryWrapper.lambda().eq(HiddenReport::getRectificationOrgId, hiddenReportPageParam.getRectificationOrgId());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getCurrentStatus())) {
            queryWrapper.lambda().eq(HiddenReport::getCurrentStatus, hiddenReportPageParam.getCurrentStatus());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getVerifyUserName())) {
            queryWrapper.lambda().like(HiddenReport::getVerifyUserName, hiddenReportPageParam.getVerifyUserName());
        }
        if(ObjectUtil.isNotEmpty(hiddenReportPageParam.getHiddenAddr())) {
            queryWrapper.lambda().like(HiddenReport::getHiddenAddr, hiddenReportPageParam.getHiddenAddr());
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getReportDateStart(),hiddenReportPageParam.getReportDateEnd())) {
            queryWrapper.lambda().between(HiddenReport::getCreateTime, DateUtil.beginOfDay(hiddenReportPageParam.getReportDateStart()), DateUtil.endOfDay(hiddenReportPageParam.getReportDateEnd()));
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getVerifyDateStart(),hiddenReportPageParam.getVerifyDateEnd())) {
            queryWrapper.lambda().between(HiddenReport::getVerifyTime, DateUtil.beginOfDay(hiddenReportPageParam.getVerifyDateStart()), DateUtil.endOfDay(hiddenReportPageParam.getVerifyDateEnd()));
        }
        // 过滤审核完成的隐患
        queryWrapper.lambda().eq(HiddenReport::getApproval, AuditStatusEnum.FINISHED.getValue());
        // 过滤较大或重大隐患
        queryWrapper.lambda().in(HiddenReport::getHiddenLevel, HiddenLevelEnum.LARGER_HIDDEN.getValue(), HiddenLevelEnum.MAJOR_HIDDEN.getValue());
        // 过滤进行中的任务
        if(ObjectUtil.isNotEmpty(reportIds)){
            queryWrapper.lambda().notIn(HiddenReport::getReportId, reportIds);
        }
        if(ObjectUtil.isAllNotEmpty(hiddenReportPageParam.getSortField(), hiddenReportPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(hiddenReportPageParam.getSortOrder());
            queryWrapper.orderBy(true, hiddenReportPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(hiddenReportPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(HiddenReport::getCreateTime);
        }
        Page<HiddenReport> result = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        return result;
    }
}
